package com.linkage.jz.bankruptcy.activity.Project;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.CreateAddrActivity;
import com.linkage.jz.bankruptcy.adapter.FileAdapter;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.MyAddr;
import com.linkage.jz.bankruptcy.bean.ProNodeInfo;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.datepicker.CustomDatePicker;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;
import com.linkage.seapeak.pojo.UploadImage;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * @author AFAP
 * 创建进度
 */
public class CreateProFlowActivity extends BaseCreateActivity implements OnClickListener {
    private static final String TAG = CreateProFlowActivity.class.getSimpleName();
    public static final String KEY_ACTION = "action";
    public static final String KEY_FLOW = "flow";
    public static final String KEY_CODE = "code";

    private int REQUEST_CODE_ADDRESS = 10001;

    private String mProjectId;
    private ProNodeInfo mProNode;
    private String mModeCode;

    private Date now, tenYearLater;//日期选择跨度10年（可修改）
    private int mTimeMode = 0; // 0：时间点， 1：时间段
    private long mTimeStart = -1, mTimeEnd = -1, mTime = -1; // 开始时间、结束时间、时间
    private String addressId = "";
    private MyAddr mAddrInfo;
    private EditText et_flow_name, et_flow_desc;
    private TextView tv_flow_address, tv_pro_flow_time, tv_pro_flow_time_start, tv_pro_flow_time_end;
    private Switch sw_pro_flow_countdown;

    private RecyclerView mImgRecyclerView;
    private List<UploadImage> mImgList = new ArrayList<>();
    private GridImagesAdapter mImgAdapter;

    @Override
    public void initData() {
        now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.YEAR, 10);
        tenYearLater = calendar.getTime();
    }

    @Override
    public void setListener() {
    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_create_pro_flow);
        super.onCreate(savedInstanceState);


        if (TextUtils.equals(getIntent().getStringExtra(KEY_ACTION), "edit")) {
            mProNode = (ProNodeInfo) getIntent().getSerializableExtra(KEY_FLOW);
            mProjectId = mProNode.getBankruptcyProjectId();
            mModeCode = mProNode.getModelCode();
        } else {
            mProjectId = getIntent().getStringExtra(KEY_PROJECTID);
            mModeCode = getIntent().getStringExtra(KEY_CODE);
        }
        if (mProNode != null) {
            mAddrInfo = mProNode.getSysAddressInfo();
            titlebar_title.setText("编辑节点");
        } else {
            titlebar_title.setText("添加节点");
        }
        initViews();

        titlebar_menu_text.setOnClickListener(this);

        getAddressList();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_ADDRESS) {
                addressId = data.getStringExtra("id");
                tv_flow_address.setText(data.getStringExtra("desc"));
                mAddrInfo = (MyAddr) data.getSerializableExtra("bean");
            }
        }
    }

    public void initViews() {
        // 特殊处理下，
        titlebar_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        titlebar_menu_text.setVisibility(View.VISIBLE);

        titlebar_back = findViewById(R.id.titlebar_back);
        et_flow_name = findViewById(R.id.et_flow_name);
        et_flow_desc = findViewById(R.id.et_flow_desc);
        tv_flow_address = findViewById(R.id.tv_flow_address);
        tv_pro_flow_time = findViewById(R.id.tv_pro_flow_time);
        tv_pro_flow_time_start = findViewById(R.id.tv_pro_flow_time_start);
        tv_pro_flow_time_end = findViewById(R.id.tv_pro_flow_time_end);
        sw_pro_flow_countdown = findViewById(R.id.sw_pro_flow_countdown);

        mImgRecyclerView = findViewById(R.id.recycler_imgs);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mImgRecyclerView.setLayoutManager(manager);
        mImgAdapter = new GridImagesAdapter(this, TYPE_EDIT);
        mImgAdapter.setList(mImgList);
        mImgRecyclerView.setAdapter(mImgAdapter);
        findViewById(R.id.area_time).setVisibility(View.VISIBLE);
        findViewById(R.id.area_time_1).setVisibility(View.VISIBLE);
        findViewById(R.id.area_time_2).setVisibility(View.GONE);

        ((RadioGroup) findViewById(R.id.rg_pro_flow_time_mode)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int which) {
                if (which == R.id.rg_pro_flow_time_mode_1) {
                    mTimeMode = 0;
                    findViewById(R.id.area_time).setVisibility(View.VISIBLE);
                    findViewById(R.id.area_time_1).setVisibility(View.VISIBLE);
                    findViewById(R.id.area_time_2).setVisibility(View.GONE);

                } else if (which == R.id.rg_pro_flow_time_mode_2) {
                    mTimeMode = 1;
                    findViewById(R.id.area_time).setVisibility(View.VISIBLE);
                    findViewById(R.id.area_time_1).setVisibility(View.GONE);
                    findViewById(R.id.area_time_2).setVisibility(View.VISIBLE);
                }
            }
        });


        if (mProNode != null) {
            et_flow_name.setText(mProNode.getNodeName());
            et_flow_desc.setText(mProNode.getNodeNote());
            addressId = mProNode.getSysAddressId();
            if (mProNode.getSysAddressInfo() != null) {
                tv_flow_address.setText(mProNode.getSysAddressInfo().getFullAddress());
            }
            if (mProNode.getTimeType() == null) {

            } else if (TextUtils.equals(mProNode.getTimeType().getValue(), "0")) {
                mTime = mProNode.getStartTime();
                if (mTime != 0) {
                    tv_pro_flow_time.setText(DateFormatUtils.long2Str(mTime, true));
                }
                findViewById(R.id.rg_pro_flow_time_mode_1).performClick();
            } else {
                if (mProNode.getStartTime() != 0) {
                    mTimeStart = mProNode.getStartTime();
                    mTimeEnd = mProNode.getEndTime();

                    tv_pro_flow_time_start.setText(DateFormatUtils.long2Str(mTimeStart, true));
                    if(mTimeEnd!=0)
                    tv_pro_flow_time_end.setText(DateFormatUtils.long2Str(mTimeEnd, true));
                }
                findViewById(R.id.rg_pro_flow_time_mode_2).performClick();
            }

            sw_pro_flow_countdown.setChecked(mProNode.isCountdown());


            for (int i = 0; i < mProNode.getAttachmentList().size(); i++) {
                TaskAtta atta = mProNode.getAttachmentList().get(i);
                JSONObject obj = new JSONObject();
                try {
                    obj.putOpt("filename", atta.getAttachmentName());
                    obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                    obj.putOpt("filesize", atta.getAttachmentSize());
                    obj.putOpt("loadUrl", atta.getAttachmentWatermarkAddress());
                    mImgList.add(new Gson().fromJson(obj.toString(), UploadImage.class));

                    BaseCreateActivity.sorFiles(mImgList,true);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        mPromptDialog = new CommonPromptDialog(this,CommonPromptDialog.TYPE_TIPS);
        mPromptDialog.setContent("放弃编辑？");
        mPromptDialog.setPositiveClickListener("是", new OnClickListener() {
            @Override
            public void onClick(View view) {
                CreateProFlowActivity.super.onBackPressed();
            }
        });
        mPromptDialog.setNegativeClickListener("否", new OnClickListener() {
            @Override
            public void onClick(View view) {
                mPromptDialog.dismiss();
            }
        });
        mPromptDialog.show();
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        CustomDatePicker mDatePicker;
        switch (view.getId()) {
            case R.id.titlebar_menu_text:
                saveData(false);
                break;
            case R.id.tv_flow_address:
                intent = new Intent(this, CreateAddrActivity.class);
                intent.putExtra(CreateAddrActivity.KEY_FROM, CreateAddrActivity.FROM_FLOW);
                if (mAddrInfo != null) {
                    intent.putExtra(CreateAddrActivity.KEY_BEAN, mAddrInfo);
                }
                startActivityForResult(intent, REQUEST_CODE_ADDRESS);
                break;
            case R.id.tv_pro_flow_time:
                mDatePicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
                    @Override
                    public void onTimeSelected(long timestamp) {
                        mTime = timestamp;
                        tv_pro_flow_time.setText(DateFormatUtils.long2Str(timestamp, true));
                    }
                }, now.getTime(), tenYearLater.getTime());
                mDatePicker.setCancelable(false);
                mDatePicker.setCanShowPreciseTime(true);
                mDatePicker.setScrollLoop(false);
                mDatePicker.setCanShowAnim(false);
                mDatePicker.show(DateFormatUtils.long2Str(mTime, true));
                break;
            case R.id.tv_pro_flow_time_start:
                mDatePicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
                    @Override
                    public void onTimeSelected(long timestamp) {
                        mTimeStart = timestamp;
                        tv_pro_flow_time_start.setText(DateFormatUtils.long2Str(timestamp, true));
                    }
                }, now.getTime(), tenYearLater.getTime());
                mDatePicker.setCancelable(false);
                mDatePicker.setCanShowPreciseTime(true);
                mDatePicker.setScrollLoop(false);
                mDatePicker.setCanShowAnim(false);
                mDatePicker.show(DateFormatUtils.long2Str(mTimeStart, true));
                break;
            case R.id.tv_pro_flow_time_end:
                mDatePicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
                    @Override
                    public void onTimeSelected(long timestamp) {
                        mTimeEnd = timestamp;
                        tv_pro_flow_time_end.setText(DateFormatUtils.long2Str(timestamp, true));
                    }
                }, now.getTime(), tenYearLater.getTime());
                mDatePicker.setCancelable(false);
                mDatePicker.setCanShowPreciseTime(true);
                mDatePicker.setScrollLoop(false);
                mDatePicker.setCanShowAnim(false);
                mDatePicker.show(DateFormatUtils.long2Str(mTimeEnd, true));
                break;
        }
    }

    private void getAddressList() {
        Network
                .getAPIService()
                .getAddressList(getUserToken(), getUserId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonArray data = json.getAsJsonArray("data");
                        if (data != null) {
                            List<MyAddr> list = MyAddr.parse(data);
                            for (int i = 0; i < list.size(); i++) {
                                if (list.get(i).isDefaut()) {
                                    addressId = list.get(i).getId();
                                    tv_flow_address.setText(list.get(i).getFullAddress());
                                    break;
                                }
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    private CommonPromptDialog mPromptDialog;
    private String tipString;
    private boolean tmpflag = false;

    private void saveData(boolean staging) {
        tipString = "公示进度信息已创建";
        if (staging) {
            tipString = "已暂存";
        }
        String flow_name = et_flow_name.getText().toString().trim();
        String flow_desc = et_flow_desc.getText().toString().trim();
        if (TextUtils.isEmpty(flow_name)) {
//            ToastUtil.showShort("节点名称不能为空");
            showToast("节点名称不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
//        if (TextUtils.isEmpty(flow_desc)) {
//            ToastUtil.showShort("节点内容不能为空");
//            return;
//        }
//        if (TextUtils.isEmpty(addressId)) {
//            ToastUtil.showShort("请选择地址");
//            return;
//        }

//        if (mTimeMode == -1) {
//            ToastUtil.showShort("请选择时间类型");
//            return;
//        }


        String mTimeStr = tv_pro_flow_time.getText().toString().trim();
        String mTimeStartStr = tv_pro_flow_time_start.getText().toString().trim();
        String mTimeEndStr = tv_pro_flow_time_end.getText().toString().trim();
        // 时间未设置，且又不选为暂存时
        if(!tmpflag) {
            if (((mTimeMode == 0 && TextUtils.isEmpty(mTimeStr))) && !staging || (mTimeMode == 1 && TextUtils.isEmpty(mTimeEndStr))) {
                // ToastUtil.showShort("请选择时间");
                mPromptDialog = new CommonPromptDialog(this, CommonPromptDialog.TYPE_TIPS);
                mPromptDialog.setContent("该节点未设置时间，债人不可见哦~");
                mPromptDialog.setPositiveClickListener("去设置", new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mPromptDialog.dismiss();
                    }
                });
                mPromptDialog.setNegativeClickListener("暂存", new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        tmpflag =true;
                        saveData(true);
                    }
                });
                mPromptDialog.show();
                return;
            }
        }

        if(!tmpflag) {
            if (mTimeMode == 1 && (TextUtils.isEmpty(mTimeStartStr) || TextUtils.isEmpty(mTimeEndStr))) {
//                ToastUtil.showShort("请选择开始时间和截止时间");
                showToast("请选择开始时间和截止时间", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
                return;
            }

            if (mTimeMode == 1 && mTimeEnd < mTimeStart) {
                showToast("截止时间不应该小于开始时间", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
//                ToastUtil.showShort("截止时间不应该小于开始时间");
                return;
            }
        }

        JSONArray fileArr = new JSONArray();
//        for (int i = 0; i < mImgList.size(); i++) {
//
//            JSONObject obj = new JSONObject();
//            try {
//                obj.putOpt("attachmentName", "相关附件"+(i+1)+".jpg");
//                obj.putOpt("attachmentDownloadAddress", mImgList.get(i).getFilepath());
//                obj.putOpt("attachmentSize", mImgList.get(i).getFilesize());
//                obj.putOpt("loadUrl", mImgList.get(i).getLoadUrl());
//                fileArr.put(obj);
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }

        for (int i = 0; i < mImgList.size(); i++) {
            if (TextUtils.equals(mImgList.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                if (FileUtil.isImage(mImgList.get(i).getFilename())) {
                    obj.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                } else {
                    obj.putOpt("attachmentName", mImgList.get(i).getFilename());
                }
                obj.putOpt("attachmentDownloadAddress", mImgList.get(i).getFilepath());
                obj.putOpt("attachmentSize", mImgList.get(i).getFilesize());
                obj.putOpt("loadUrl", mImgList.get(i).getLoadUrl());
                fileArr.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        mShapeLoadingDialog.setLoadingText("提交信息中...");
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();

        Observable<JsonObject> observable;
        if (mProNode != null) {
            tipString = "公示进度信息已更新";
            observable = Network
                    .getAPIService()
                    .editFlow(getUserToken(), mProNode.getId(), mProjectId, flow_name, flow_desc, mTimeMode == 0 ?
                                    mTimeStr : mTimeStartStr, mTimeEndStr, mModeCode,
                             String.valueOf(mTimeMode), addressId, staging, sw_pro_flow_countdown.isChecked(), fileArr.toString());
        } else {
            observable = Network
                    .getAPIService()
                    .createFlow(getUserToken(), mProjectId, flow_name, flow_desc, mTimeMode == 0 ? mTimeStr :
                                    mTimeStartStr, mTimeEndStr, mModeCode,
                           String.valueOf(mTimeMode), addressId, staging, sw_pro_flow_countdown.isChecked(), fileArr.toString());
        }

        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_FLOW);
                        EventBus.getDefault().post(event);
//                        ToastUtil.showShort(tipString);
                        showToast("提交成功", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.SUCCESS);
                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });

    }
}

